import { logOutApi } from "@/api/auth";
import { getUserInfoApi } from "@/api/main";
import router from "@/router";

export default defineStore("user", () => {
  const token = ref(localStorage.getItem("token"));
  const username = ref("");
  const level = ref(-1);
  const userId = ref(0);
  const isAdmin = computed(() => token.value && level.value === 1);
  const isLogin = computed(() => !!token.value && userId.value !== 0);
  watchEffect(() => {
    if (token.value) {
      localStorage.setItem("token", token.value);
    } else {
      localStorage.removeItem("token");
    }
  });
  const setUserInfo = async () => {
    try {
      const { data } = await getUserInfoApi();
      userId.value = data.data.id;
      level.value = data.data.level;
      username.value = data.data.username;
      return true;
    } catch (e) {
        clearStorage();
      console.log(e);
      // 把路由定向到登录页，无需等待直接reload
      return false;
    }
  };
  const logOut = (type: number) => {
    if (type) {
      clearStorage();
      // 把路由定向到登录页，无需等待直接reload
      toLogin();
    } else {
      // 通知服务器 将token拉黑
      logOutApi()
        .then(() => {
          clearStorage();
          // 把路由定向到登录页，无需等待直接reload
          toLogin();
        })
        .catch(() => {
          console.log("退出失败!");
        });
    }
  };
  const toLogin = () => {
    if (router.currentRoute.value.path === "/login") {
      return;
    }
    router.push({ path: "/login", replace: true });
  };
  /* 清理数据 */
  const clearStorage = () => {
    token.value = "";
    sessionStorage.clear();
  };
  return {
    username,
    isLogin,
    token,
    level,
    isAdmin,
    setUserInfo,
    logOut,
  };
});
